package com.tusuo.stds.ui.pay;

import android.app.Activity;
import android.content.Context;
import android.icu.text.SimpleDateFormat;
import android.os.Message;
import android.util.Base64;

import com.alipay.sdk.app.PayTask;
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mobileqq.openpay.api.IOpenApi;
import com.tencent.mobileqq.openpay.api.OpenApiFactory;
import com.tencent.mobileqq.openpay.constants.OpenConstants;
import com.tencent.mobileqq.openpay.data.pay.PayApi;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.AttachDataResult;
import com.tusuo.stds.rest.PayParam;
import com.tusuo.stds.rest.QQPayParam;
import com.tusuo.stds.rest.TenPayParam;
import com.tusuo.stds.util.Utils;

import java.io.UnsupportedEncodingException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;

/**
 * Created by developer on 17-4-26.
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(MyPayPresenter.class)
public class MyPayPresenter extends MvpBasePresenter<MyPayView> {

    @Inject
    ApiHelper mApiHelper;

    Context context;

    int payNum = 0;
    private final String APP_KEY = "zHfSpp72XrP11HHa";
    private IOpenApi openApi;

    public MyPayPresenter(Context context) {
        this.context = context;
        Injector.initMyPayPresenterComponent().inject(this);
        openApi = OpenApiFactory.getInstance(context, Constants.QQ_APP_ID);
    }

    public void initData(int id,String payType,float money) {
        if ("unlock".equals(payType)) {
            mApiHelper.getSceneUnlockAttachData(new MyPaySubscriber(),id);
        }else if ("reward".equals(payType)) {
            if (money != 0) {
                mApiHelper.getSceneRewardAttachData(new MyPaySubscriber(),id,(int)money);
            }
        }else if ("vip".equals(payType)) {
            mApiHelper.getVipAttachData(new MyPaySubscriber(),id);
        }
    }

    public void startPayAction(String attachData,String payType) {
        if ("TenPayForApp".equals(payType)) {
            if (Utils.App.isWxAppSupported(context)) {
                mApiHelper.getTenPayParam(new GetTenPayParamSubscriber(),payType,attachData);
            }else {
                Utils.UI.showToastShort("请手动打开微信后再进行支付");
            }
        }else if ("AlipayForApp".equals(payType)) {
            mApiHelper.getPayParam(new GetPayParamSubscriber(),payType,attachData);
        }else if ("QQPayForAndroidApp".equals(payType)) {
            mApiHelper.getQQPayParam(new GetQQPayParamSubscriber(),payType,attachData);
        }
    }

    public IOpenApi getOpenApi() {
        return openApi;
    }


    private class MyPaySubscriber extends Subscriber<AttachDataResult> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(AttachDataResult attachDataResult) {
            getView().startPay(attachDataResult.AttachData);
        }
    }

    private class GetQQPayParamSubscriber extends Subscriber<QQPayParam> {


        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(QQPayParam qqPayParam) {
            payByQQ(qqPayParam.Credential);
        }
    }

    private class GetTenPayParamSubscriber extends Subscriber<TenPayParam> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(TenPayParam tenPayParam) {
            payByWeChat(tenPayParam.Credential);
        }
    }


    private class GetPayParamSubscriber extends Subscriber<PayParam> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(final PayParam payParam) {
            getView().payByAliPay(payParam.Credential);
        }
    }

    private void payByWeChat(TenPayParam.CredentialBean credential) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context,credential.AppId);

        PayReq payReq = new PayReq();
        payReq.appId        = credential.AppId;
        payReq.partnerId	= credential.PartnerId;
        payReq.prepayId		= credential.PrepayId;
        payReq.nonceStr		= credential.NonceStr;
        payReq.timeStamp	= credential.TimeStamp;
        payReq.packageValue	= credential.Package;
        payReq.sign			= credential.Sign;

        iwxapi.sendReq(payReq);
    }

    private void payByQQ(QQPayParam.CredentialBean credential){
        PayApi api = new PayApi();
        boolean isSupport = openApi.isMobileQQInstalled() && openApi.isMobileQQSupportApi(OpenConstants.API_NAME_PAY);
        if (isSupport) {

            api.serialNumber = "" + payNum ++; // 支付序号,用于标识此次支付
            api.pubAcc = ""; // 手Q公众帐号id.参与支付签名，签名关键字key为pubAcc
            api.pubAccHint = ""; // 支付完成页面，展示给用户的提示语：提醒关注公众帐号
            api.appId = credential.appId;
            api.tokenId = credential.tokenId;
            api.callbackScheme = "qwallet1105825787"; // QQ钱包支付结果回调给urlscheme为callbackScheme的activity.，参看后续的“支付回调结果处理”
            api.nonce = credential.nonce; // 随机字段串，每次支付时都要不一样.参与支付签名，签名关键字key为nonce
            api.timeStamp = Long.parseLong(credential.timeStamp) / 1000; // 时间戳，为1970年1月1日00:00到请求发起时间的秒数
            api.bargainorId = credential.bargainorId; // 商户号.参与支付签名，签名关键字key为bargainorId
            api.sig = credential.sign; // 商户Server下发的数字签名，生成的签名串，参看“数字签名”
            api.sigType = "HMAC-SHA1"; // 签名时，使用的加密方式，默认为"HMAC-SHA1"
        }

    /*    try {
            signApi(api);
        } catch (Exception e) {
            e.printStackTrace();
        }*/


        if (api.checkParams()) {
            openApi.execApi(api);
        }
    }

    public void signApi(PayApi api) throws Exception {
        // 按key排序
        StringBuilder stringBuilder = new StringBuilder();
        /*stringBuilder.append("appId=").append(api.appId);
        stringBuilder.append("&bargainorId=").append(api.bargainorId);
        stringBuilder.append("&nonce=").append(api.nonce);
        stringBuilder.append("&pubAcc=").append("");
        stringBuilder.append("&tokenId=").append(api.tokenId);*/
        stringBuilder.append("appId=100619284&nonce=ksjfwierwfjk&tokenId=1000000002&pubAcc=&bargainorId=1900000109");

        byte[] byteKey = ("d139ae6fb0175e5659dce2a7c1fe84d5&").getBytes("UTF-8");
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(byteKey, "HmacSHA1");
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] byteSrc = stringBuilder.toString().getBytes("UTF-8");
        // 完成 Mac 操作
        byte[] dst = mac.doFinal(byteSrc);
        // Base64
        api.sig = Base64.encodeToString(dst, Base64.NO_WRAP);
        api.sigType = "HMAC-SHA1";

    }

}
